package cxp.utils;

import cxp.entity.Tables;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.util.List;
import java.util.ResourceBundle;
import java.util.regex.Pattern;

/**
 * Created by cunxp on 2018/5/24.
 */
public class GeneratoeUtil {

    public static String ERROR = "ERROR";
    public static String OK = "OK";

    /**
     * 判断 字符串是否是英文字母或者下划线构成
     * @param str
     * @return
     */
    public static String checkCharacter(String str){
        String pattern = "^[A-Za-z]\\w+?";
        boolean isMatch = Pattern.matches(pattern, str);
        if(isMatch){
            return OK;
        }else {
            return "必须是英文字母开头并且由字母或者下划线构成！";
        }
    }
    /**
     * 判断 包命名
     * @param str
     * @return
     */
    public static String checkPackageCharacter(String str){
        String pattern = "^[a-z]+?\\.[a-z]+?$";
        boolean isMatch = Pattern.matches(pattern, str);
        if(isMatch){
            return OK;
        }else {
            return "必须符合Java包命名规范！";
        }
    }

    /**
     * 分割java包名称 转化成路径
     * @param str
     * @return
     */
    public static String splitPackageCharacter(String str){
        String res = "";
        String[] arr = str.split("\\.");
        for (String string:arr) {
            res += string + "/";
        }
        return res;
    }

    /**
     * 生成 pom文件 以及各级目录
     * @param projectName
     * @param packageName
     * @return
     */
    public static void step1(String projectName,String packageName){
//        String rootPath = System.getProperty("user.dir");
        String rootPath = "F:\\virtual";
        String pomStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
                "\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n" +
                "\t<modelVersion>4.0.0</modelVersion>\n" +
                "\n" +
                "\t<groupId>"+packageName+"</groupId>\n" +
                "\t<artifactId>"+projectName+"</artifactId>\n" +
                "\t<version>0.0.1-SNAPSHOT</version>\n" +
                "\t<packaging>jar</packaging>\n" +
                "\n" +
                "\t<name>"+projectName+"</name>\n" +
                "\t<description>Demo project for Spring Boot</description>\n" +
                "\n" +
                "\t<parent>\n" +
                "\t\t<groupId>org.springframework.boot</groupId>\n" +
                "\t\t<artifactId>spring-boot-starter-parent</artifactId>\n" +
                "\t\t<version>2.0.2.RELEASE</version>\n" +
                "\t\t<relativePath/> <!-- lookup parent from repository -->\n" +
                "\t</parent>\n" +
                "\n" +
                "\t<properties>\n" +
                "\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n" +
                "\t\t<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n" +
                "\t\t<java.version>1.8</java.version>\n" +
                "\t</properties>\n" +
                "\n" +
                "\t<dependencies>\n" +
                "\t\t<dependency>\n" +
                "\t\t\t<groupId>org.springframework.boot</groupId>\n" +
                "\t\t\t<artifactId>spring-boot-starter-web</artifactId>\n" +
                "\t\t\t<!-- 排除内置容器，排除内置容器导出成war包可以让外部容器运行spring-boot项目-->\n" +
                "\t\t\t<!--<exclusions>\n" +
                "\t\t\t\t<exclusion>\n" +
                "\t\t\t\t\t<groupId>org.springframework.boot</groupId>\n" +
                "\t\t\t\t\t<artifactId>spring-boot-starter-tomcat</artifactId>\n" +
                "\t\t\t\t</exclusion>\n" +
                "\t\t\t</exclusions>-->\n" +
                "\t\t</dependency>\n" +
                "\t\t<dependency>\n" +
                "\t\t\t<groupId>org.mybatis.spring.boot</groupId>\n" +
                "\t\t\t<artifactId>mybatis-spring-boot-starter</artifactId>\n" +
                "\t\t\t<version>1.3.2</version>\n" +
                "\t\t</dependency>\n" +
                "\t\t<dependency>\n" +
                "\t\t\t<groupId>org.springframework.boot</groupId>\n" +
                "\t\t\t<artifactId>spring-boot-starter-test</artifactId>\n" +
                "\t\t\t<scope>test</scope>\n" +
                "\t\t</dependency>\n" +
                "\t\t<!--热部署-->\n" +
                "\t\t<dependency>\n" +
                "\t\t\t<groupId>org.springframework.boot</groupId>\n" +
                "\t\t\t<artifactId>spring-boot-devtools</artifactId>\n" +
                "\t\t\t<optional>true</optional>\n" +
                "\t\t</dependency>\n" +
                "\t\t<!--fastjson配置-->\n" +
                "\t\t<dependency>\n" +
                "\t\t\t<groupId>com.alibaba</groupId>\n" +
                "\t\t\t<artifactId>fastjson</artifactId>\n" +
                "\t\t\t<version>1.2.46</version>\n" +
                "\t\t</dependency>\n" +
                "\t\t<!--apache commons lang3-->\n" +
                "\t\t<dependency>\n" +
                "\t\t\t<groupId>org.apache.commons</groupId>\n" +
                "\t\t\t<artifactId>commons-lang3</artifactId>\n" +
                "\t\t\t<version>3.7</version>\n" +
                "\t\t</dependency>\n" +
                "\t\t<!--apache commons collects-->\n" +
                "\t\t<dependency>\n" +
                "\t\t\t<groupId>org.apache.commons</groupId>\n" +
                "\t\t\t<artifactId>commons-collections4</artifactId>\n" +
                "\t\t\t<version>4.1</version>\n" +
                "\t\t</dependency>\n" +
                "\t\t<!--日志-->\n" +
                "\t\t<dependency>\n" +
                "\t\t\t<groupId>org.springframework.boot</groupId>\n" +
                "\t\t\t<artifactId>spring-boot-starter-logging</artifactId>\n" +
                "\t\t</dependency>\n" +
                "\t\t<!--数据库-->\n" +
                "\t\t<dependency>\n" +
                "\t\t\t<groupId>mysql</groupId>\n" +
                "\t\t\t<artifactId>mysql-connector-java</artifactId>\n" +
                "\t\t\t<scope>runtime</scope>\n" +
                "\t\t</dependency>\n" +
                "\t\t<!-- alibaba的druid数据库连接池 -->\n" +
                "\t\t<dependency>\n" +
                "\t\t\t<groupId>com.alibaba</groupId>\n" +
                "\t\t\t<artifactId>druid</artifactId>\n" +
                "\t\t\t<version>1.0.11</version>\n" +
                "\t\t</dependency>\n" +
                "\t\t<dependency>\n" +
                "\t\t\t<groupId>org.springframework.boot</groupId>\n" +
                "\t\t\t<artifactId>spring-boot-starter-data-jpa</artifactId>\n" +
                "\t\t\t<version>RELEASE</version>\n" +
                "\t\t</dependency>\n" +
                "\t\t<!--jpa-->\n" +
                "\t\t<dependency>\n" +
                "\t\t\t<groupId>org.springframework.boot</groupId>\n" +
                "\t\t\t<artifactId>spring-boot-starter-data-jpa</artifactId>\n" +
                "\t\t</dependency>\n" +
                "\t</dependencies>\n" +
                "\n" +
                "\t<build>\n" +
                "\t\t<plugins>\n" +
                "\t\t\t<plugin>\n" +
                "\t\t\t\t<groupId>org.springframework.boot</groupId>\n" +
                "\t\t\t\t<artifactId>spring-boot-maven-plugin</artifactId>\n" +
                "\t\t\t\t<configuration>\n" +
                "\t\t\t\t\t<!--热部署-->\n" +
                "\t\t\t\t\t<fork>true</fork>\n" +
                "\t\t\t\t</configuration>\n" +
                "\t\t\t</plugin>\n" +
                "\t\t</plugins>\n" +
                "\t</build>\n" +
                "</project>\n";
        String mainPropertiesStr = "server:\n" +
                "  port: 8080\n" +
                "# 数据库配置\n" +
                "spring:\n" +
                "    datasource:\n" +
                "#连接池 初始化大小、最小、最大\n" +
                "        initialSize: 5\n" +
                "        minIdle: 5\n" +
                "        maxActive: 20\n" +
                "#配置获取连接等待超时的时间\n" +
                "        maxWait: 60000\n" +
                "#配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒\n" +
                "        timeBetweenEvictionRunsMillis: 60000\n" +
                "#配置一个连接在池中最小生存的时间，单位是毫秒\n" +
                "        minEvictableIdleTimeMillis: 300000\n" +
                "#其他设置\n" +
                "        validationQuery: SELECT 1 FROM DUAL\n" +
                "        testWhileIdle: true\n" +
                "        testOnBorrow: false\n" +
                "        testOnReturn: false\n" +
                "#打开PSCache，并且指定每个连接上PSCache的大小\n" +
                "        poolPreparedStatements: true\n" +
                "        maxOpenPreparedStatements: 20\n" +
                "#配置监控统计拦截的filters，去掉后监控界面sql无法统计，'wall'用于防火墙\n" +
                "        filters: stat,wall,log4j\n" +
                "#通过connectProperties属性来打开mergeSql功能；慢SQL记录\n" +
                "        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000\n" +
                "#合并多个DruidDataSource的监控数据\n" +
                "        useGlobalDataSourceStat: true\n" +
                "#spring mvc 配置\n" +
                "    mvc:\n" +
                "      view:\n" +
                "        prefix: /\n" +
                "        suffix: .html\n" +
                "#JPA 配置\n" +
                "    jpa:\n" +
                "#控制台打印sql\n" +
                "      show-sql: false\n" +
                "      generate-ddl : true\n" +
                "# Hibernate ddl auto (create, create-drop, update)\n" +
                "      hibernate :\n" +
                "        ddl-auto : update\n" +
                "#命名规则\n" +
                "        naming :\n" +
                "          implicit-strategy : org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl\n" +
                "          physical-strategy : org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl\n" +
                "          strategy : org.hibernate.cfg.ImprovedNamingStrategy\n" +
                "#乱码解决\n" +
                "    http:\n" +
                "      encoding:\n" +
                "        charset: utf-8\n" +
                "        force: true\n" +
                "#激活配置文件\n" +
                "    profiles:\n" +
                "      active: prod\n" +
                "\n" +
                "#logging\n" +
                "#logging:\n" +
                "#  level: trace\n" +
                "#mybatis:\n" +
                "#  mapper-locations: classpath:mapper/*.xml\n" +
                "#  type-aliases-package: com.cxp.beans\n" +
                "\n" +
                "#pagehelper:\n" +
                "#    helperDialect: mysql\n" +
                "#    reasonable: true\n" +
                "#    supportMethodsArguments: true\n" +
                "#    params: count=countSql";
        String devPropertiesStr = "# 数据库配置\n" +
                "spring:\n" +
                "    datasource:\n" +
                "        url: jdbc:mysql://ip:3306/cxp?characterEncoding=utf8&useSSL=false\n" +
                "        username: root\n" +
                "        password: 123456\n" +
                "        type: com.alibaba.druid.pool.DruidDataSource\n" +
                "        driver-class-name: com.mysql.jdbc.Driver\n" +
                "\n" +
                "#JPA 配置\n" +
                "    jpa:\n" +
                "      database: MYSQL\n" +
                "#控制台打印sql\n" +
                "      show-sql: false\n" +
                "      hibernate :\n" +
                "#方言\n" +
                "        dialect : org.hibernate.dialect.MySQL5Dialect";
        String bannerStr = "  ____ ___  _________\n" +
                "_/ ___\\\\  \\/  /\\____ \\\n" +
                "\\  \\___ >    < |  |_> >\n" +
                " \\___  >__/\\_ \\|   __/\n" +
                "     \\/      \\/|__|";
        String testStr = "package "+packageName+";\n" +
                "\n" +
                "import org.junit.Test;\n" +
                "import org.junit.runner.RunWith;\n" +
                "import org.springframework.boot.test.context.SpringBootTest;\n" +
                "import org.springframework.test.context.junit4.SpringRunner;\n" +
                "\n" +
                "@RunWith(SpringRunner.class)\n" +
                "@SpringBootTest\n" +
                "public class ApplicationTests {\n" +
                "\n" +
                "\t@Test\n" +
                "\tpublic void contextLoads() {\n" +
                "\t}\n" +
                "\n" +
                "}\n";
        String mainInStr = "package "+packageName+";\n" +
                "\n" +
                "import org.springframework.boot.SpringApplication;\n" +
                "import org.springframework.boot.autoconfigure.SpringBootApplication;\n" +
                "import org.springframework.boot.builder.SpringApplicationBuilder;\n" +
                "import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;\n" +
                "import org.springframework.context.annotation.ComponentScan;\n" +
                "\n" +
                "@SpringBootApplication\n" +
                "public class Application{\n" +
                "\n" +
                "\n" +
                "\tpublic static void main(String[] args) {\n" +
                "\t\tSpringApplication.run(Application.class, args);\n" +
                "\t}\n" +
                "}\n";
        String defaultViewStr = "package "+packageName+";\n" +
                "\n" +
                "import org.springframework.context.annotation.Configuration;\n" +
                "import org.springframework.core.Ordered;\n" +
                "import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;\n" +
                "import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;\n" +
                "\n" +
                "\n" +
                "@Configuration\n" +
                "public class WebConfig extends WebMvcConfigurerAdapter {\n" +
                "    @Override\n" +
                "    public void addViewControllers(ViewControllerRegistry registry) {\n" +
                "        registry.addViewController( \"/\" ).setViewName(\"forward:/index.html\");\n" +
                "        registry.addViewController( \"/index\" ).setViewName(\"forward:/index.html\");\n" +
                "        registry.setOrder( Ordered.HIGHEST_PRECEDENCE );\n" +
                "        super.addViewControllers( registry );\n" +
                "    }\n" +
                "}\n";
        try {
            //controller
            File controllerFolder = new File(rootPath + File.separator
                    + "src/main/java/" + splitPackageCharacter(packageName) + "/controller");
            controllerFolder.mkdirs();
            //entity
            File entityFolder = new File(rootPath + File.separator
                    + "src/main/java/" + splitPackageCharacter(packageName) + "/entity");
            controllerFolder.mkdirs();
            //repository
            File repositoryFolder = new File(rootPath + File.separator
                    + "src/main/java/" + splitPackageCharacter(packageName) + "/repository");
            repositoryFolder.mkdirs();
            //service impl
            File serviceFolder = new File(rootPath + File.separator
                    + "src/main/java/" + splitPackageCharacter(packageName) + "/service/impl");
            serviceFolder.mkdirs();
            //resource
            File resourceFolder = new File(rootPath + File.separator + "src/main/resources/static");
            resourceFolder.mkdirs();
            //test
            File testFolder = new File(rootPath + File.separator + "src/test/java/" + splitPackageCharacter(packageName));
            testFolder.mkdirs();
            //主入口
            File mainIn = new File(rootPath + File.separator
                    + "src/main/java/" + splitPackageCharacter(packageName) + "/Application.java");
            FileUtils.writeStringToFile(mainIn,mainInStr,"utf-8");
            File defaultView = new File(rootPath + File.separator
                    + "src/main/java/" + splitPackageCharacter(packageName) + "/WebConfig.java");
            FileUtils.writeStringToFile(defaultView,defaultViewStr,"utf-8");
            //单元测试文件
            File testFile = new File(rootPath + File.separator + "src/test/java/" + splitPackageCharacter(packageName) + "ApplicationTests.java");
            FileUtils.writeStringToFile(testFile,testStr,"utf-8");
            //配置文件
            File mainProperties = new File(rootPath + File.separator + "src/main/resources/application.yml");
            File devProperties = new File(rootPath + File.separator + "src/main/resources/application-dev.yml");
            File banner = new File(rootPath + File.separator + "src/main/resources/banner.txt");
            FileUtils.writeStringToFile(mainProperties,mainPropertiesStr,"utf-8");
            FileUtils.writeStringToFile(devProperties,devPropertiesStr,"utf-8");
            FileUtils.writeStringToFile(banner,bannerStr,"utf-8");
            //pom文件
            File pom = new File(rootPath + File.separator + "pom.xml");
            FileUtils.writeStringToFile(pom,pomStr,"utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成实体类
     * @param projectName
     * @param packageName
     * @return
     */
    public static void step2(String projectName,String packageName){
        ResourceBundle resource = ResourceBundle.getBundle("pro");
        String type = resource.getString("database.type");
        if("mysql".equalsIgnoreCase(type)){
            EntityUtils.generatorPojo();
        }else {
            throw new RuntimeException("暂不支持其他数据库类型！");
        }
    }

    /**
     * 生成repository service 以及impl
     * @param projectName
     * @param packageName
     * @return
     */
    public static void step3(String projectName,String packageName){
        ResourceBundle resource = ResourceBundle.getBundle("pro");
        String key = resource.getString("database.type");
        System.out.println(key);
    }

    public static void main(String[] args) {
//        step1("ha","com.cxp");
//        step2();
    }
}
